package com.message.Baidu_ai_API.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Random;

public class FileSetUtil {
    public static String resetFileName(final Integer id,String path,MultipartFile image) throws IOException {
        System.out.println(path);

        // 生成新的文件名
    long timestamp = System.currentTimeMillis();
    Random random = new Random();
    int randomNumber = random.nextInt(1000); // 生成一个 0 到 999 之间的随机数

    // 构建新的文件名
    String newFileName = id + "_" + timestamp + "_" + randomNumber;
        File newFile = new File(path, newFileName+".png");
        try (InputStream is = image.getInputStream();
             FileOutputStream fos = new FileOutputStream(newFile)) {

            byte[] buffer = new byte[1024];
            int bytesRead;

            // 从源文件读取并写入目标文件
            while ((bytesRead = is.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }

            System.out.println("文件保存成功: " + newFile.getAbsolutePath());
            return newFileName;
        } catch (IOException e) {
            throw new IOException("文件保存失败: " + e.getMessage(), e);
        }
}
    public static File saveFile(MultipartFile file, String path, String fileName) {
        File newFile = new File(path, fileName+".png");
        File parentDir = newFile.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            parentDir.mkdirs(); // 创建所有必要的父目录
        }
        try (InputStream is = file.getInputStream();
             FileOutputStream fos = new FileOutputStream(newFile)) {

            byte[] buffer = new byte[1024];
            int bytesRead;

            // 从源文件读取并写入目标文件
            while ((bytesRead = is.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
            return newFile;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
